package com.gzhu.knowledgeAdmin.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzhu.knowledgeAdmin.common.result.ErrorCode;
import com.gzhu.knowledgeAdmin.common.result.R;
import com.gzhu.knowledgeAdmin.common.utils.ResponseUtil;
import com.gzhu.knowledgeAdmin.common.utils.UserInfoUtils;
import com.gzhu.knowledgeAdmin.entity.SecurityUser;
import com.gzhu.knowledgeAdmin.entity.User;
import com.gzhu.knowledgeAdmin.security.TokenManager;
import com.gzhu.knowledgeAdmin.service.XtyhService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 登录过滤器，继承UsernamePasswordAuthenticationFilter，对用户名密码进行登录校验
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;
    private TokenManager tokenManager;
    private StringRedisTemplate stringRedisTemplate;
    private XtyhService xtyhService;

    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, StringRedisTemplate redisTemplate,XtyhService xtyhService) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.stringRedisTemplate = redisTemplate;
        this.xtyhService = xtyhService;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/knowledgeAdmin/xtyh/login","POST"));
    }



    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {
        try {
            User user = new ObjectMapper().readValue(req.getInputStream(), User.class);


            // 判断登录用户是否已经分配了角色，如果没有，则禁止登录
            int grantType = xtyhService.hasGrantedRole(user.getUserName());
            // 账号存在，但未分配
            if (grantType==-1){
                ResponseUtil.out(res, R.error(ErrorCode.NO_ROLE));
                return null;
            }else if(grantType==-2){ // 账号不存在
                ResponseUtil.out(res, R.error(ErrorCode.USERNAMEPASSWORD_ERROR));
                return null;
            }


            // 验证验证码
            boolean captcha  = xtyhService.validate(user.getUuid(),user.getCaptcha());

            if(!captcha){
                ResponseUtil.out(res, R.error(ErrorCode.CAPTCHA_ERROR));
                return null;
            }

            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword(), new ArrayList<>()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 登录成功
     * @param req
     * @param res
     * @param chain
     * @param auth
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) {
        SecurityUser user = (SecurityUser) auth.getPrincipal();
        String token = tokenManager.createToken(user.getCurrentUserInfo().getUserName());

        // 缓存权限信息
        stringRedisTemplate.opsForValue().set(user.getCurrentUserInfo().getUserName(), JSON.toJSONString(user.getPermissionValueList()),24*60*60*1000, TimeUnit.MILLISECONDS);

        // 缓存用户信息
        stringRedisTemplate.opsForValue().set("userInfo_"+user.getCurrentUserInfo().getUserName(),JSON.toJSONString(user.getCurrentUserInfo()),24*60*60*1000, TimeUnit.MILLISECONDS);

        ResponseUtil.out(res, R.ok(token));
    }

    /**
     * 登录失败
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
                                              AuthenticationException e) throws IOException, ServletException {
        ResponseUtil.out(response, R.error(ErrorCode.USERNAMEPASSWORD_ERROR));
    }
}
